// SearchScreen.kt
package com.example.receiptocr.profile

import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.receiptocr.viewModels.UserProfileState
import com.example.receiptocr.viewModels.UserProfileViewModel
import com.example.receiptocr.buttons.PrimaryButton
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.material.SnackbarHostState
import androidx.compose.ui.platform.LocalContext
import java.time.Instant
import java.time.LocalDate
import java.time.temporal.ChronoUnit

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileScreen(navController: NavController, userProfileViewModel: UserProfileViewModel = hiltViewModel()) {
    val userProfileState by userProfileViewModel.userProfileState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    val context = LocalContext.current
    
    // 编辑状态
    var isEditing by remember { mutableStateOf(false) }
    var editedUsername by remember { mutableStateOf("") }
    var editedEmail by remember { mutableStateOf("") }
    var editedPhone by remember { mutableStateOf("") }
    
    // 密码修改对话框状态
    var showPasswordDialog by remember { mutableStateOf(false) }
    var oldPassword by remember { mutableStateOf("") }
    var newPassword by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    
    // 系统设置对话框状态
    var showSettingsDialog by remember { mutableStateOf(false) }
    var darkMode by remember { mutableStateOf(false) }
    var notificationsEnabled by remember { mutableStateOf(true) }

    // 在Composable首次启动时获取用户资料
    LaunchedEffect(Unit) {
        userProfileViewModel.fetchUserProfile()
    }

    // 监听错误信息并通过Snackbar展示
    LaunchedEffect(userProfileState) {
        if (userProfileState is UserProfileState.Error) {
            val errorMessage = (userProfileState as UserProfileState.Error).error
            snackbarHostState.showSnackbar(errorMessage)
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("个人中心") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.background
                )
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(color = MaterialTheme.colorScheme.background)
                .padding(paddingValues)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(16.dp)
            ) {
                when (userProfileState) {
                    is UserProfileState.Loading -> {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(100.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }

                    is UserProfileState.Success -> {
                        val userProfile = (userProfileState as UserProfileState.Success).userProfile
                        
                        // 用户基本信息卡片
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 16.dp),
                            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp)
                            ) {
                                // 用户名
                                if (isEditing) {
                                    TextField(
                                        value = editedUsername,
                                        onValueChange = { editedUsername = it },
                                        label = { Text("用户名") },
                                        modifier = Modifier.fillMaxWidth()
                                    )
                                } else {
                                    Text(
                                        text = userProfile.username,
                                        style = MaterialTheme.typography.headlineSmall,
                                        color = MaterialTheme.colorScheme.onSurface,
                                        modifier = Modifier.padding(bottom = 8.dp)
                                    )
                                }
                                
                                // 注册天数
                                Text(
                                    text = "您已注册${calculateRegistrationDays(userProfile.registerDate)}天啦",
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    modifier = Modifier.padding(bottom = 16.dp)
                                )
                                
                                // 编辑按钮
                                Button(
                                    onClick = { isEditing = !isEditing },
                                    modifier = Modifier.align(Alignment.End)
                                ) {
                                    Text(if (isEditing) "保存" else "编辑资料")
                                }
                            }
                        }
                        
                        // 功能列表
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 16.dp),
                            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                        ) {
                            Column(modifier = Modifier.fillMaxWidth()) {
                                // 修改密码
                                ListItem(
                                    headlineContent = { Text("修改密码") },
                                    leadingContent = {
                                        Icon(
                                            Icons.Default.Lock,
                                            contentDescription = "修改密码",
                                            tint = MaterialTheme.colorScheme.primary
                                        )
                                    },
                                    trailingContent = {
                                        Icon(Icons.Default.ChevronRight, contentDescription = null)
                                    },
                                    modifier = Modifier.clickable { showPasswordDialog = true }
                                )
                                
                                Divider()
                                
                                // 系统设置
                                ListItem(
                                    headlineContent = { Text("系统设置") },
                                    leadingContent = {
                                        Icon(
                                            Icons.Default.Settings,
                                            contentDescription = "系统设置",
                                            tint = MaterialTheme.colorScheme.primary
                                        )
                                    },
                                    trailingContent = {
                                        Icon(Icons.Default.ChevronRight, contentDescription = null)
                                    },
                                    modifier = Modifier.clickable { showSettingsDialog = true }
                                )
                            }
                        }
                        
                        // 退出登录按钮
                        PrimaryButton(
                            onClick = {
                                userProfileViewModel.clearUserProfile()
                                navController.navigate("login") {
                                    popUpTo("profile") { inclusive = true }
                                }
                            },
                            modifier = Modifier.fillMaxWidth(),
                            text = "退出登录"
                        )
                    }

                    is UserProfileState.Error -> {
                        // 错误状态处理
                    }

                    is UserProfileState.Idle -> {
                        // 初始状态处理
                    }
                }
            }
        }
    }
    
    // 密码修改对话框
    if (showPasswordDialog) {
        AlertDialog(
            onDismissRequest = { showPasswordDialog = false },
            title = { Text("修改密码") },
            text = {
                Column {
                    TextField(
                        value = oldPassword,
                        onValueChange = { oldPassword = it },
                        label = { Text("当前密码") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    TextField(
                        value = newPassword,
                        onValueChange = { newPassword = it },
                        label = { Text("新密码") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    TextField(
                        value = confirmPassword,
                        onValueChange = { confirmPassword = it },
                        label = { Text("确认新密码") },
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        // TODO: 实现密码修改逻辑
                        showPasswordDialog = false
                    }
                ) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(onClick = { showPasswordDialog = false }) {
                    Text("取消")
                }
            }
        )
    }
    
    // 系统设置对话框
    if (showSettingsDialog) {
        AlertDialog(
            onDismissRequest = { showSettingsDialog = false },
            title = { Text("系统设置") },
            text = {
                Column {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("深色模式")
                        Switch(
                            checked = darkMode,
                            onCheckedChange = { darkMode = it }
                        )
                    }
                    Spacer(modifier = Modifier.height(8.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("通知提醒")
                        Switch(
                            checked = notificationsEnabled,
                            onCheckedChange = { notificationsEnabled = it }
                        )
                    }
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        // TODO: 保存系统设置
                        showSettingsDialog = false
                    }
                ) {
                    Text("保存")
                }
            },
            dismissButton = {
                TextButton(onClick = { showSettingsDialog = false }) {
                    Text("取消")
                }
            }
        )
    }
}

// 添加日期计算扩展函数
fun calculateRegistrationDays(registerDateString: String): Int {
    val registerDate = LocalDate.parse(registerDateString)
    val currentDate = LocalDate.now()
    return ChronoUnit.DAYS.between(registerDate, currentDate).toInt()
}